/* * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.franmontiel.persistentcookiejar.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;

import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.ResourceTable;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.List;

/**
 * This is the main ability slice class have the main user interface of the app
 */
public class MainAbilitySlice extends AbilitySlice {
    private Text text;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(),
                new SharedPrefsCookiePersistor(this));
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                .build();
        text = (Text) findComponentById(ResourceTable.Id_tvResponse);
        TextField tfUrl = (TextField) findComponentById(ResourceTable.Id_tfUrl);
        findComponentById(ResourceTable.Id_btnGetData).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String url = tfUrl.getText();
                getResponse(okHttpClient, url);
            }
        });
    }

    /**
     * This method is used to get cookies from response
     *
     * @param client OkHttpClient to get cookies from response
     * @param url Http URL
     */
    private void getResponse(OkHttpClient client, String url) {
        // code request code here
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException exception) {
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (response != null && response.body() != null) {
                    List<String> cookieList = response.headers("Set-Cookie");
                    StringBuilder stringBuilder = new StringBuilder();
                    if (cookieList.size() > 0) {
                        for (String cookie : cookieList) {
                            stringBuilder.append(cookie).append(",");
                        }
                    }
                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            text.setText("Response: " + stringBuilder.toString());
                        }
                    });
                }
            }
        });
    }
}